package cn.iune.erp.payment;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.DataUtils;
import com.justep.baas.data.Row;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.common.base.BaseJPAImpl;


@Repository
public class AccountPaymentDaoJPAImpl extends BaseJPAImpl<AccountPayment> implements IAccountPaymentDao {

//	private final Logger log = LoggerFactory.getLogger(AccountPaymentDaoJPAImpl.class);

//	private String kSql;
//	@PersistenceContext 
//	private EntityManager em ;
	
	@Override
	public void insert(AccountPayment obj) {
		em.persist(obj);
	}

	@Override
	public void delete(String fID) {
		em.remove(em.getReference(AccountPayment.class, fID));
	}

	@Override
	public AccountPayment update(AccountPayment obj) {
		AccountPayment objNew = em.merge(obj);
		return objNew;
	}

	@Override
	public AccountPayment getByID(String fID) {
		AccountPayment singleResult = em.find(AccountPayment.class, fID);
		return singleResult;
	}

	@Override
	public List<AccountPayment> getAll() {
		Query query = em.createNamedQuery("AccountPayment.findAll");
		@SuppressWarnings("unchecked")
		List<AccountPayment> resultList = query.getResultList();
		return resultList;
	}

	@Override
	public List<AccountPayment> getByMasterID(String fMasterID) {
		// TODO Auto-generated method stub
		String kSql="SELECT AccountPayment FROM AccountPayment AccountPayment WHERE AccountPayment.fMasterID=:fMasterID";
		Query query = em.createQuery(kSql);
		query.setParameter("fMasterID", fMasterID);
		@SuppressWarnings("unchecked")
		List<AccountPayment> resultList = query.getResultList();
		return resultList;
	}


	
	@Override
	public JSONObject create(JSONObject data) {
		//缺省列
		String defColstr = Utils.getDefCols(AccountPayment.class);
		data.put("defColstr", defColstr);
		return Utils.newData(data);

	}

	@Override
	public JSONObject query(JSONObject data) throws SQLException {
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
		String fMasterID = data.getString("fMasterID");
//		log.info("limit-->"+limit);
//		log.info("offset-->"+offset);
//		log.info("filters-->"+filters);
//		log.info("sqlParams-->"+params);
		/*
		limit-->15
		offset-->0
		filters-->[unitCode LIKE ? OR unitName LIKE ? OR unitType LIKE ?]
		sqlParams-->[%3%, %3%, %3%]
		*/		
		
		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT AccountPayment FROM AccountPayment AccountPayment %s %s ";
		String select = "AccountPayment.*";
		String from = "AccountPayment AccountPayment";

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("accountPaymentNo LIKE ? OR comments LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 2; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("AccountPayment.fID='"+id+"'");
		}
		//处理fMasterID
//		System.out.println("fMasterID-->"+fMasterID);
		if (Utils.isNotEmptyString(fMasterID)) {
			filters.add("AccountPayment.fMasterID='"+fMasterID+"'");
		}
		
		//处理条件过滤
		JSONArray filterList = data.getJSONArray("filters"); // 列定义
		if(filterList!=null && filterList.size()>0){
			for(int i=0;i<filterList.size();i++){
				JSONObject jsonFilter = filterList.getJSONObject(i);
//				System.out.println("jsonFilter.getString(\"filter\")-->"+jsonFilter.getString("filter"));
				filters.add(jsonFilter.getString("filter"));
			}
		}
		
		String where = "";
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		
//		System.out.println("where-->"+where);

		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = Utils.isNotEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		
//		Connection conn = DataUtils.getConnection(DataUtils.DATASOURCE_1);
		Connection conn = super.getConnection();
		String sqlTotal = String.format(format, "COUNT(*)", from, where, "");
		Object total = DataUtils.getValueBySQL(conn, sqlTotal, sqlParams);
		//SELECT AccountPayment.fID FROM AccountPayment AccountPayment    LIMIT 0,-1//为-1时报错。
		if(limit==-1){
			limit = Integer.parseInt(total.toString());
		}
		
//		Table table = DataUtils.queryData(conn, tableName, columns, filters, orderBy, params, offset, limit);
		Table table = DataUtils.queryData(conn, sql, sqlParams, columns, offset, limit);

		table.setTotal(Integer.parseInt(total.toString()));
		table.setOffset(offset);
		table.setTableName("AccountPayment");
		
		JSONObject json = Transform.tableToJson(table);
		//////////////////////////////////自定义聚合数据开始/////////////////////////////////
		//////////////////////////////////////////////////////////////////////////////
		String aggregateSelect = "";
		
		JSONObject aggregateColumns = data.getJSONObject("aggregateColumns"); // 聚合列定义
//		System.out.println("aggregateColumns-->"+aggregateColumns);
		if(aggregateColumns!=null){
			
			Set<String> keys = aggregateColumns.keySet();
			int index = 0;
			for(String key:keys){
				if(index==0){
					aggregateSelect = aggregateSelect + "SUM(" + key + ") as " + aggregateColumns.getJSONObject(key).getString("name");
				}else{
					aggregateSelect = aggregateSelect + ",SUM(" + key + ") as " + aggregateColumns.getJSONObject(key).getString("name");
				}
				
				index++;
			}
			
//			aggregateSelect = "SUM(StorageItem.quantityL) as sumQuantityL,SUM(CONVERT(FileItem.costingAmountPer*StorageItem.quantityL,decimal(38,2))) as sumCostingAmount,SUM(StorageItem.pieceQuantityL) as sumPieceQuantityL";
			
		}
		
//		String aggregate = data.getString("aggregate");
//		if(aggregate!=null){
//			if(aggregateSelect.equals("")){
//				aggregateSelect = aggregate;
//			}else{
//				aggregateSelect = aggregateSelect + "," + aggregate;
//			}
//		}
		
//		System.out.println("aggregateSelect-->"+aggregateSelect);
		
		if(!aggregateSelect.equals("")){
			//如果select不为空
			
			String aggregateSql = String.format(format, aggregateSelect, from, where, "");
//			System.out.println("aggregateSql-->"+aggregateSql);
			Table aggregateTable = DataUtils.queryData(conn, aggregateSql, sqlParams, aggregateColumns, 0, table.getTotal());
//			Row row = aggregateTable.getRows().get(0);
//			JSONObject aggregateValues = Transform.rowToJson(aggregateTable, row);
			JSONObject jo = Transform.tableToJson(aggregateTable);
			JSONArray jarray = jo.getJSONArray("rows");
			JSONObject aggregateValues = new JSONObject();
			if(jarray.size()>0){
				aggregateValues = jarray.getJSONObject(0);
			}
//			System.out.println("aggregateValues-->"+aggregateValues);
			//jb-->{"userdata":{"recordState":"none"},"costingAmount":{"value":"599517613.43"},"costingAmountPer":{"value":"59957.893727"}}
			json.put("aggregateValues", aggregateValues);
		}
		//////////////////////////////////////////////////////////////////////////////////
		////////////////////////////自定义聚合数据结束////////////////////////////////////
		
		//关闭连接
		conn.close();
		return json;
	}


	@Override
	public JSONObject querySimple(JSONObject data) throws SQLException {
		
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
		String fMasterID = data.getString("fMasterID");
//		log.info("limit-->"+limit);
//		log.info("offset-->"+offset);
//		log.info("filters-->"+filters);
//		log.info("sqlParams-->"+params);
		/*
		limit-->15
		offset-->0
		filters-->[unitCode LIKE ? OR unitName LIKE ? OR unitType LIKE ?]
		sqlParams-->[%3%, %3%, %3%]
		*/		
		
		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT AccountPayment FROM AccountPayment AccountPayment %s %s ";
		String select = "AccountPayment.*";
		String from = "AccountPayment AccountPayment";

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("accountPaymentNo LIKE ? OR comments LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 2; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("AccountPayment.fID='"+id+"'");
		}
		//处理fMasterID
//		System.out.println("fMasterID-->"+fMasterID);
		if (Utils.isNotEmptyString(fMasterID)) {
			filters.add("AccountPayment.fMasterID='"+fMasterID+"'");
		}
		
		//处理条件过滤
		JSONArray filterList = data.getJSONArray("filters"); // 列定义
		if(filterList!=null && filterList.size()>0){
			for(int i=0;i<filterList.size();i++){
				JSONObject jsonFilter = filterList.getJSONObject(i);
//				System.out.println("jsonFilter.getString(\"filter\")-->"+jsonFilter.getString("filter"));
				filters.add(jsonFilter.getString("filter"));
			}
		}
		
		String where = "";
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		
//		System.out.println("where-->"+where);

		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = Utils.isNotEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		
//		Connection conn = DataUtils.getConnection(DataUtils.DATASOURCE_1);
		Connection conn = super.getConnection();
		String sqlTotal = String.format(format, "COUNT(*)", from, where, "");
		Object total = DataUtils.getValueBySQL(conn, sqlTotal, sqlParams);
		//SELECT AccountPayment.fID FROM AccountPayment AccountPayment    LIMIT 0,-1//为-1时报错。
		if(limit==-1){
			limit = Integer.parseInt(total.toString());
		}
		
//		Table table = DataUtils.queryData(conn, tableName, columns, filters, orderBy, params, offset, limit);
		Table table = DataUtils.queryData(conn, sql, sqlParams, columns, offset, limit);
		
		//关闭连接
		conn.close();

		table.setTotal(Integer.parseInt(total.toString()));
		table.setOffset(offset);
		table.setTableName("AccountPayment");
		
		//JSONObject json = Transform.tableToJson(table);
		
		JSONArray arrayItem = new JSONArray();

		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			AccountPayment obj = JSON.toJavaObject(javaObject, AccountPayment.class);
			
			arrayItem.add(obj);
		}
		
		JSONObject json = new JSONObject();
		
		json.put("data", arrayItem);
		json.put("total", Integer.parseInt(total.toString()));
		json.put("code", 0);
		json.put("msg", "success");
		
		return json;
	}

	//用于登记应收月档
	@Override
	public List<AccountPayment> getActualSKD(Date dateStart, Date dateEnd, String enterpriseNo) {
		// TODO Auto-generated method stub
		String	kSql="SELECT AccountPayment"
				+ " FROM AccountPayment AccountPayment "
				+ " WHERE  AccountPayment.audit = 'confirm' "
				+ " AND  AccountPayment.orderDate >= :dateStart  "
				+ " AND  AccountPayment.orderDate <= :dateEnd  "
				+ " AND  AccountPayment.retailFlag = 0  " //不包含零售
				+ " AND  AccountPayment.enterpriseNo = :enterpriseNo  "
				+ " AND ( AccountPayment.billType = 'SKDJ' OR AccountPayment.billType = 'YSKD') "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("dateStart", dateStart);
		query.setParameter("dateEnd", dateEnd);
		query.setParameter("enterpriseNo", enterpriseNo);
		@SuppressWarnings("unchecked")
		List<AccountPayment> resultList = query.getResultList();
		return resultList;
	}

	//用于登记应付月档
	@Override
	public List<AccountPayment> getActualFKD(Date dateStart, Date dateEnd, String enterpriseNo) {
		// TODO Auto-generated method stub
		String	kSql="SELECT AccountPayment"
				+ " FROM AccountPayment AccountPayment "
				+ " WHERE  AccountPayment.audit = 'confirm' "
				+ " AND  AccountPayment.orderDate >= :dateStart  "
				+ " AND  AccountPayment.orderDate <= :dateEnd  "
				+ " AND  AccountPayment.retailFlag = 0  " //不包含零售
				+ " AND  AccountPayment.enterpriseNo = :enterpriseNo  "
				+ " AND ( AccountPayment.billType = 'FKDJ' OR AccountPayment.billType = 'YFKD') "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("dateStart", dateStart);
		query.setParameter("dateEnd", dateEnd);
		query.setParameter("enterpriseNo", enterpriseNo);
		@SuppressWarnings("unchecked")
		List<AccountPayment> resultList = query.getResultList();
		return resultList;
	}

	//用于登记应收月档
	@Override
	public List<AccountPayment> getActualSKD(String customerID, Date dateStart, Date dateEnd, String enterpriseNo) {
		// TODO Auto-generated method stub
		String	kSql="SELECT AccountPayment"
				+ " FROM AccountPayment AccountPayment "
				+ " WHERE  AccountPayment.audit = 'confirm' "
				+ " AND  AccountPayment.orderDate >= :dateStart  "
				+ " AND  AccountPayment.orderDate <= :dateEnd  "
				+ " AND  AccountPayment.customerID = :customerID  "
				+ " AND  AccountPayment.enterpriseNo = :enterpriseNo  "
				+ " AND ( AccountPayment.billType = 'SKDJ' OR AccountPayment.billType = 'YSKD') "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("dateStart", dateStart);
		query.setParameter("dateEnd", dateEnd);
		query.setParameter("customerID", customerID);
		query.setParameter("enterpriseNo", enterpriseNo);
		@SuppressWarnings("unchecked")
		List<AccountPayment> resultList = query.getResultList();
		return resultList;
	}

	//用于登记应付月档
	@Override
	public List<AccountPayment> getActualFKD(String customerID, Date dateStart, Date dateEnd, String enterpriseNo) {
		// TODO Auto-generated method stub
		String	kSql="SELECT AccountPayment"
				+ " FROM AccountPayment AccountPayment "
				+ " WHERE  AccountPayment.audit = 'confirm' "
				+ " AND  AccountPayment.orderDate >= :dateStart  "
				+ " AND  AccountPayment.orderDate <= :dateEnd  "
				+ " AND  AccountPayment.customerID = :customerID  "
				+ " AND  AccountPayment.enterpriseNo = :enterpriseNo  "
				+ " AND ( AccountPayment.billType = 'FKDJ' OR AccountPayment.billType = 'YFKD') "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("dateStart", dateStart);
		query.setParameter("dateEnd", dateEnd);
		query.setParameter("customerID", customerID);
		query.setParameter("enterpriseNo", enterpriseNo);
		@SuppressWarnings("unchecked")
		List<AccountPayment> resultList = query.getResultList();
		return resultList;
	}

	//可用于查询收款单/收退单/预收款单/付款单/付退单/预付款单/收款核销/付款核销
	@Override
	public AccountPayment getByNo(String accountPaymentNo/* , String billType */, String enterpriseNo) {
		// TODO Auto-generated method stub
		String	kSql="SELECT AccountPayment FROM AccountPayment AccountPayment "
				+ " WHERE ( AccountPayment.accountPaymentNo = :accountPaymentNo ) "
//				+ " AND ( AccountPayment.billType = :billType ) "
				+ " AND ( AccountPayment.enterpriseNo = :enterpriseNo ) "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("accountPaymentNo", accountPaymentNo);
//		query.setParameter("billType", billType);
		query.setParameter("enterpriseNo", enterpriseNo);
		
		AccountPayment singleResult = null;
		try {
			singleResult = (AccountPayment) query.getSingleResult();
		} catch (NoResultException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return singleResult;
	}


//	@Override
//	public AccountPayment getSKDJByNo(String accountPaymentNo, String enterpriseNo) {
//		String	kSql="SELECT AccountPayment FROM AccountPayment AccountPayment "
//				+ " WHERE ( AccountPayment.accountPaymentNo = :accountPaymentNo ) "
//				+ " AND ( AccountPayment.billType ='SKDJ' ) "
//				+ " AND ( AccountPayment.enterpriseNo = :enterpriseNo ) "
//				;
//		Query query = em.createQuery(kSql);
//		query.setParameter("accountPaymentNo", accountPaymentNo);
//		query.setParameter("enterpriseNo", enterpriseNo);
//		AccountPayment singleResult = null;
//		try {
//			singleResult = (AccountPayment) query.getSingleResult();
//		} catch (NoResultException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return singleResult;
//	}

//	@Override
//	public AccountPayment getYSKDByNo(String accountPaymentNo, String enterpriseNo) {
//		String	kSql="SELECT AccountPayment FROM AccountPayment AccountPayment "
//				+ " WHERE ( AccountPayment.accountPaymentNo = :accountPaymentNo ) "
//				+ " AND ( AccountPayment.billType ='YSKD' ) "
//				+ " AND ( AccountPayment.enterpriseNo = :enterpriseNo ) "
//				;
//		Query query = em.createQuery(kSql);
//		query.setParameter("accountPaymentNo", accountPaymentNo);
//		query.setParameter("enterpriseNo", enterpriseNo);
//		AccountPayment singleResult = null;
//		try {
//			singleResult = (AccountPayment) query.getSingleResult();
//		} catch (NoResultException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return singleResult;
//	}


//	@Override
//	public AccountPayment getRDJQByNo(String accountPaymentNo, String enterpriseNo) {
//		String	kSql="SELECT AccountPayment FROM AccountPayment AccountPayment "
//				+ " WHERE ( AccountPayment.accountPaymentNo = :accountPaymentNo ) "
//				+ " AND ( AccountPayment.billType ='RDJQ' ) "
//				+ " AND ( AccountPayment.enterpriseNo = :enterpriseNo ) "
//				;
//		Query query = em.createQuery(kSql);
//		query.setParameter("accountPaymentNo", accountPaymentNo);
//		query.setParameter("enterpriseNo", enterpriseNo);
//		AccountPayment singleResult = null;
//		try {
//			singleResult = (AccountPayment) query.getSingleResult();
//		} catch (NoResultException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return singleResult;
//	}

//	@Override
//	public AccountPayment getYFKDByNo(String accountPaymentNo, String enterpriseNo) {
//		String	kSql="SELECT AccountPayment FROM AccountPayment AccountPayment "
//				+ " WHERE ( AccountPayment.accountPaymentNo = :accountPaymentNo ) "
//				+ " AND ( AccountPayment.billType ='YFKD' ) "
//				+ " AND ( AccountPayment.enterpriseNo = :enterpriseNo ) "
//				;
//		Query query = em.createQuery(kSql);
//		query.setParameter("accountPaymentNo", accountPaymentNo);
//		query.setParameter("enterpriseNo", enterpriseNo);
//		AccountPayment singleResult = null;
//		try {
//			singleResult = (AccountPayment) query.getSingleResult();
//		} catch (NoResultException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return singleResult;
//	}

//	@Override
//	public AccountPayment getYSKDByOriginNo(String originNo, String enterpriseNo) {
//		String	kSql="SELECT AccountPayment FROM AccountPayment AccountPayment "
//				+ " WHERE ( AccountPayment.originNo = :originNo ) "
//				+ " AND ( AccountPayment.origin ='XSDD' ) "
//				+ " AND ( AccountPayment.billType ='YSKD' ) "
//				+ " AND ( AccountPayment.enterpriseNo = :enterpriseNo ) "
//				;
//		Query query = em.createQuery(kSql);
//		query.setParameter("originNo", originNo);
//		query.setParameter("enterpriseNo", enterpriseNo);
//		AccountPayment singleResult = null;
//		try {
//			singleResult = (AccountPayment) query.getSingleResult();
//		} catch (NoResultException e) {
//			// TODO Auto-generated catch block
//			return null;
//		}
//		return singleResult;
//	}


	//获取未核销的预收款单列表（不包含会员充值，按照单据时间的从小到大排序）
	@Override
	public List<AccountPayment> getUnclearYSKDList(String guestNumber, String enterpriseNo) {
		String	kSql="SELECT AccountPayment FROM AccountPayment AccountPayment "
				+ " WHERE ( AccountPayment.guestNumber = :guestNumber ) "
				+ " AND ( AccountPayment.billType ='YSKD' ) "
				+ " AND ( AccountPayment.enterpriseNo = :enterpriseNo ) "
				+ " AND ( AccountPayment.audit='confirm' ) "
				+ " AND ( AccountPayment.pendingAmount>0 ) "
				/////////////////////////////////////////////////
				+ " AND ( AccountPayment.clearType='4' ) "
				/////////////////////////////////////////////////
				+ " ORDER BY AccountPayment.confirmDate ASC "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("guestNumber", guestNumber);
		query.setParameter("enterpriseNo", enterpriseNo);
		@SuppressWarnings("unchecked")
		List<AccountPayment> resultList = query.getResultList();
		return resultList;
	}

	//获取会员余额列表（按照单据时间的从小到大排序）
	@Override
	public List<AccountPayment> getUnclearYECZList(String customerID, String enterpriseNo) {
		String	kSql="SELECT AccountPayment FROM AccountPayment AccountPayment "
				+ " WHERE ( AccountPayment.customerID = :customerID ) "
				+ " AND ( AccountPayment.billType ='YSKD' ) "
//				+ " AND ( AccountPayment.enterpriseNo = :enterpriseNo ) "
				+ " AND ( AccountPayment.audit='confirm' ) "
				+ " AND ( AccountPayment.pendingAmount>0 ) "
				/////////////////////////////////////////////////
				+ " AND ( AccountPayment.clearType='Y' ) "
				/////////////////////////////////////////////////
				+ " ORDER BY AccountPayment.confirmDate ASC "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("customerID", customerID);
//		query.setParameter("enterpriseNo", enterpriseNo);
		@SuppressWarnings("unchecked")
		List<AccountPayment> resultList = query.getResultList();
		return resultList;
	}

	//预收款单余额
	/*
	@Override
	public BigDecimal getUnclearYSKDAmount(String customerID, String enterpriseNo) {
		// TODO Auto-generated method stub
		String sql = "SELECT SUM(AccountPayment.pendingAmount) "
				+ " FROM AccountPayment AccountPayment "
				+ " WHERE AccountPayment.billType='YSKD' "
				+ " AND AccountPayment.enterpriseNo = :enterpriseNo "
				+ " AND AccountPayment.audit='confirm' "
				+ " AND AccountPayment.pendingAmount>0 "
				+ " AND AccountPayment.customerID = :customerID "
				;
		Query query = em.createQuery(sql);
		//给参数赋值
//		for(int i=0;i<params.size();i++){
//			query.setParameter(i, params.get(i));
//		}
		query.setParameter("enterpriseNo", customerID);
		query.setParameter("customerID", enterpriseNo);
		
		BigDecimal singleResult =  (BigDecimal) query.getSingleResult();
		return singleResult;
	}
	*/

	//今日收款金额
	@Override
	public BigDecimal getRecAmountToday(List<Object> params) {
		// TODO Auto-generated method stub
		String sql = "SELECT SUM(AccountPayment.accountClearActual) "
				+ " FROM AccountPayment AccountPayment "
				+ " WHERE (AccountPayment.billType='SKDJ' OR AccountPayment.billType='STDJ' OR AccountPayment.billType='YSKD') "
				+ " AND AccountPayment.audit='confirm' "
//				+ " AND AccountPayment.status='open' "
				+ " AND AccountPayment.enterpriseNo = :enterpriseNo "
				+ " AND AccountPayment.confirmDate = :confirmDate "
				;
		Query query = em.createQuery(sql);
		//给参数赋值
//		for(int i=0;i<params.size();i++){
//			query.setParameter(i, params.get(i));
//		}
		query.setParameter("enterpriseNo", params.get(0));
		query.setParameter("confirmDate", params.get(1));
		
		BigDecimal singleResult =  (BigDecimal) query.getSingleResult();
		return singleResult;
	}

	//今日付款金额
	@Override
	public BigDecimal getPayAmountToday(List<Object> params) {
		// TODO Auto-generated method stub
		String sql = "SELECT SUM(AccountPayment.accountClearActual) "
				+ " FROM AccountPayment AccountPayment "
				+ " WHERE (AccountPayment.billType='FKDJ' OR AccountPayment.billType='FTDJ' OR AccountPayment.billType='YFKD') "
				+ " AND AccountPayment.audit='confirm' "
//				+ " AND AccountPayment.status='open' "
				+ " AND AccountPayment.enterpriseNo = :enterpriseNo "
				+ " AND AccountPayment.confirmDate = :confirmDate "
				;
		Query query = em.createQuery(sql);
		//给参数赋值
//		for(int i=0;i<params.size();i++){
//			query.setParameter(i, params.get(i));
//		}
		query.setParameter("enterpriseNo", params.get(0));
		query.setParameter("confirmDate", params.get(1));
		
		BigDecimal singleResult =  (BigDecimal) query.getSingleResult();
		return singleResult;
	}

	@Override
	public List<AccountPayment> getByWriteOffNo(String writeOffNo, String enterpriseNo) {
		// TODO Auto-generated method stub
		String	kSql="SELECT AccountPayment FROM AccountPayment AccountPayment "
				+ " WHERE ( AccountPayment.accountPaymentNo = :accountPaymentNo ) "
				+ " AND ( AccountPayment.enterpriseNo = :enterpriseNo ) "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("accountPaymentNo", writeOffNo);
		query.setParameter("enterpriseNo", enterpriseNo);
		@SuppressWarnings("unchecked")
		List<AccountPayment> resultList = query.getResultList();
		return resultList;
	}

}
